package network.websocket;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import util.ChannelHelper;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 信道管理器
 * 完成对已经建立链接的客户端进行管理
 *
 * @author wyl
 */
public class ChannelManager {
    private static ChannelGroup GlobalGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static ConcurrentMap<String, ChannelId> ChannelMap = new ConcurrentHashMap();

    public static void addChannel(Channel channel) {
        GlobalGroup.add(channel);
        ChannelMap.put(ChannelHelper.getConnId(channel), channel.id());
    }

    public static void removeChannel(Channel channel) {
        GlobalGroup.remove(channel);
        ChannelMap.remove(ChannelHelper.getConnId(channel));
    }

    public static Channel getChannel(String channelLongId) {
        return GlobalGroup.find(ChannelMap.get(channelLongId));
    }

    public static ChannelGroup getChannelGroup() {
        return GlobalGroup;
    }

    public static boolean closeConnect(String connId) {
        Channel channel = getChannel(connId);
        if (channel != null) {
            channel.close();
            return true;
        }
        return false;
    }

}
